<template>
  <!-- 表单弹窗：添加/修改 -->
  <InventoryStockForm ref="formRefInventoryStock" @success="handleSuccess" />
  <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading"
           label-width="0px" :inline-message="true">
    <el-row>
      <el-form-item>
        <el-button @click="openDialog" type="primary" round :disabled="!isDisabled() && disabledSub">批量新增</el-button>
        <el-button @click="handleAdd" round :disabled="!isDisabled() && disabledSub">新建明细</el-button>
      </el-form-item>
    </el-row>
    <el-table :data="formData" border show-summary :summary-method="getSummaries" class="-mt-10px" style="height: 470px;">
      <el-table-column label="序号" type="index" align="center" width="55" />
<!--       <el-table-column label="来源订单" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.sourceOrderId`" :rules="formRules.sourceOrderId" class="mb-0px!">
            <el-input v-model="row.sourceOrderId" placeholder="请输入来源订单id" />
          </el-form-item>
        </template>
      </el-table-column>-->
      <el-table-column label="存货编码" min-width="150">
        <template #header>
          <span style="color: red; margin-right: 4px">*</span>
          <span>存货编码</span>
        </template>
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryCode`" :rules="formRules.inventoryCode" class="mb-0px!">
            <el-select v-model="row.inventoryCode" filterable remote :remote-method="remoteInventory"
                       :disabled="isDisabled() || disabledSub" class="!w-220px">
              <template #header>
                <el-table :data="inventoryList" border height="300px"
                          @row-click="inventoryChange(row,$event)">
                  <el-table-column align="center" label="存货编码" prop="code" min-width="120"/>
                  <el-table-column align="center" label="存货名称" prop="name" min-width="120"/>
                  <el-table-column align="center" label="规格型号" prop="specModel" min-width="120"/>
                  <el-table-column align="center" label="计量单位" prop="unitName" min-width="120"/>
                  <el-table-column align="center" label="品牌" prop="brand" min-width="120"/>
                  <el-table-column align="center" label="现存量" prop="quantity" min-width="90"/>
                </el-table>
              </template>
              <el-option :disabled="true" :value="''" />
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="存货名称" min-width="150">
        <template #header>
          <span style="color: red; margin-right: 4px">*</span>
          <span>存货名称</span>
        </template>
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryName`" :rules="formRules.inventoryName" class="mb-0px!">
            <el-input v-model="row.inventoryName" :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="规格型号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.specModel`" :rules="formRules.specModel" class="mb-0px!">
            <el-input v-model="row.specModel" :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="计量单位" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.unitId`" :rules="formRules.unitId" class="mb-0px!">
            <el-select v-model="row.unitId" placeholder="" suffix-icon="" :disabled="true">
              <el-option v-for="item in unitList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="货位" min-width="150">
        <template #header>
          <span style="color: red; margin-right: 4px">*</span>
          <span>货位</span>
        </template>
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.locationId`" :rules="formRules.locationId" class="mb-0px!">
            <el-select v-model="row.locationId" clearable filterable :loading="selectLoading"
                       @focus="remoteLocation(row.inventoryId)" @change="row.batch=undefined;row.availableAmount=0"
                       :disabled="isDisabled() || disabledSub" class="!w-220px">
              <el-option v-for="item in locationList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="批号" min-width="220">
        <template #header>
          <span style="color: red; margin-right: 4px">*</span>
          <span>批号</span>
        </template>
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.batch`" :rules="formRules.batch" class="mb-0px!">
            <el-select v-model="row.batch" filterable :loading="selectLoading"
                       @focus="remoteBatch(row.inventoryId,row.locationId)" @change="batchChange(row,$event)"
                       :disabled="isDisabled() || disabledSub" class="!w-220px">
              <el-option v-for="item in batchList" :key="item.batchCode" :label="item.batchCode" :value="item.batchCode"/>
            </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="可用量" min-width="100">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.availableAmount`" class="mb-0px!">
            <el-input v-model="row.availableAmount" type="number" :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="数量" min-width="150">
        <template #header>
          <span style="color: red; margin-right: 4px">*</span>
          <span>数量</span>
        </template>
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.quantity`" :rules="formRules.quantity" class="mb-0px!">
            <el-input v-model="row.quantity" @change="row.money=(row.quantity * row.price)" @input="maxQuantity(row)"
                      type="number" :disabled="isDisabled()" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单价" min-width="150">
        <template #header>
          <span style="color: red; margin-right: 4px">*</span>
          <span>单价</span>
        </template>
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.price`" :rules="formRules.price" class="mb-0px!">
            <el-input v-model="row.price" @change="row.money=(row.quantity * row.price)"
                      type="number" :disabled="isDisabled()" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="金额" min-width="150">
        <template #header>
          <span style="color: red; margin-right: 4px">*</span>
          <span>金额</span>
        </template>
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.money`" :rules="formRules.money" class="mb-0px!">
            <el-input v-model="row.money" @change="row.price=(row.money / row.quantity)"
                      type="number" :disabled="isDisabled()" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`" :rules="formRules.remark" class="mb-0px!">
            <el-input v-model="row.remark" :disabled="isDisabled()" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="来源批号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.sourceBatch`" :rules="formRules.sourceBatch" class="mb-0px!">
            <el-input v-model="row.sourceBatch" :disabled="isDisabled()" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60" v-if="!isDisabled()">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
<!--  <el-row justify="center" class="mt-3">
    <el-button @click="handleAdd" round>+ 添加材料出库子</el-button>
  </el-row>-->
</template>
<script setup lang="ts">
import InventoryStockForm from '../../inventory/components/InventoryStock.vue'
import { Rdrecord11Api } from '@/api/wms/rdrecord11'
import {useRoute} from "vue-router";
import {InventoryStockVO, InventoryStockApi} from "@/api/wms/inventory/stock";
import {UnitVO, UnitApi} from "@/api/wms/unit";
import { StockApi } from '@/api/wms/stock'
import {LocationVO, LocationApi} from "@/api/wms/location";

const props = defineProps<{
  orderId: undefined // 订单id（主表的关联字段）
  warehouseId: undefined // 仓库id
}>()
const formLoading = ref(false) // 表单的加载中
const selectLoading = ref(false) // 下拉框的加载中
const formData = ref([])
const formRules = reactive({
  orderId: [{ required: true, message: '订单不能为空', trigger: 'blur' }],
  inventoryCode: [{ required: true, message: '', trigger: 'change' }],
  inventoryName: [{ required: true, message: '', trigger: 'change' }],
  quantity: [{ required: true, message: '', trigger: 'blur' }],
  price: [{ required: true, message: '', trigger: 'blur' }],
  money: [{ required: true, message: '', trigger: 'blur' }],
  locationId: [{ required: true, message: '', trigger: 'blur' }],
  batch: [{ required: true, message: '', trigger: 'blur' }],
})
const route = useRoute();
const formRef = ref() // 表单 Ref
const formRefInventoryStock = ref();
const inventoryList = ref<InventoryStockVO[]>([]) // 存货数据
const unitList = ref<UnitVO[]>([]) // 计量单位数据
const locationList = ref<LocationVO[]>([]) // 货位数据
interface batchVO {
  batchCode: string // 批号
  qty: number // 可用量
}
const batchList = ref<batchVO[]>([]) // 批号数据
const disabledSub = ref(false) // 禁用明细

/** 合计 */
const getSummaries = (param) => {
  const { data } = param
  let sums = []
  sums[0] = '合计'
  sums[8] = 0
  sums[9] = 0
  sums[10] = 0
  data.forEach((data) => {
    if (data.quantity) {
      sums[8] = sums[8] + Number(data.quantity)
    }
    if (data.price) {
      sums[9] = sums[9] + Number(data.price)
    }
    if (data.money) {
      sums[10] = sums[10] + Number(data.money)
    }
  })
  return sums
}

/** 查询存货 */
const remoteInventory = (query: string) => {
  if (query) {
    setTimeout(async () => {
      inventoryList.value = await InventoryStockApi.getInventoryStockSimpleList(query)
    }, 200)
  } else {
    setTimeout(async () => {
      const data = await InventoryStockApi.getInventoryStockPage({})
      inventoryList.value = data.list
    }, 100)
  }
}

/** 查询货位 */
const remoteLocation = (id:number) => {
  if (id) {
    setTimeout(async () => {
      locationList.value = await LocationApi.getListByWarehouse(id, props.warehouseId)
    }, 100)
  } else {
    batchList.value =[]
  }
}

/** 查询批号 */
const remoteBatch = (id:number,locationId:number) => {
  if (id && locationId) {
    setTimeout(async () => {
      batchList.value = await StockApi.findUseListByParam({inventoryId: id, warehouseId: props.warehouseId, locationId: locationId})
    }, 100)
  }
}

/** 最大数量 */
const maxQuantity = (row) => {
  if (row.quantity > row.availableAmount) {
    row.quantity = row.availableAmount
  }
}

/** 选择存货 */
const inventoryChange = (row,value) => {
  row.inventoryId = value.id
  row.inventoryCode = value.code
  row.inventoryName = value.name
  row.specModel = value.specModel
  row.unitId = value.unitId
  row.locationId = undefined
  row.batch = undefined
}

/** 选择批次 */
const batchChange = (row,value) => {
  const selectedBatch = batchList.value.find(item => item.batchCode === value);
  if (selectedBatch) {
    row.availableAmount = selectedBatch.qty
    maxQuantity(row)
  }
}

/** 权限判定 */
const isDisabled = () => {
  if (route.query.type) {
    return route.query.type === 'view'
  }
  return true
}

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.orderId,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      formData.value = await Rdrecord11Api.getRdrecords11ListByOrderId(val)
      setTimeout(() => {
        if (route.query.type === 'update') {
          formData.value.forEach((data) => {
            data.availableAmount = data.quantity + data.availableAmount
          })
        }
      }, 200)
    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)
watch(
  () => props.warehouseId,
  async (val) => {
    if (!val) {
      disabledSub.value = true
      return;
    }
    disabledSub.value = false
  },
  { immediate: true }
)


const openDialog = () => {
  //打开
  formRefInventoryStock.value.open();
};

const handleSuccess = (val) => {
  try {
    formLoading.value = true;
    val.value.forEach((data) => {
      let inventory = {
        id: undefined,
        orderId: props.orderId,
        inventoryId: data.id,
        inventoryName: data.name,
        inventoryCode: data.code,
        specModel: data.specModel,
        unitId: data.unitId,
      };
      formData.value.push(inventory)
    })
  } finally {
    formLoading.value = false;
  }
};

/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    orderId: undefined,
    sourceOrderId: undefined,
    inventoryId: undefined,
    unitId: undefined,
    locationId: undefined,
    batch: undefined,
    availableAmount: undefined,
    quantity: undefined,
    price: undefined,
    money: undefined,
    remark: undefined,
    sourceBatch: undefined,
  }
  row.orderId = props.orderId
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

/** 初始化 **/
onMounted(async () => {
  // 加载计量列表
  unitList.value = await UnitApi.getUnitSimpleList()
  locationList.value = await LocationApi.getLocationSimpleList()
  //handleAdd()
})
defineExpose({ validate, getData })
</script>
